package com.yihu.wlyy.service.app.medicines;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.doctor.Doctor;
import com.yihu.wlyy.entity.doctor.DoctorMedicalRecordsPart;
import com.yihu.wlyy.entity.doctor.DoctorMedicalRecordsPartItem;
import com.yihu.wlyy.entity.patient.PatientMedicalRecords;
import com.yihu.wlyy.entity.patient.PatientMedicalRecordsItem;
import com.yihu.wlyy.repository.ConsultDao;
import com.yihu.wlyy.repository.DoctorDao;
import com.yihu.wlyy.repository.DoctorMedicalRecordsPartDao;
import com.yihu.wlyy.repository.DoctorMedicalRecordsPartItemDao;
import com.yihu.wlyy.repository.PatientMedicalRecordsDao;
import com.yihu.wlyy.repository.PatientMedicalRecordsItemDao;
import com.yihu.wlyy.service.BaseService;

/**
 * 病历夹业务处理类
 * @author George
 *
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class MedicalRecordsService extends BaseService {

	@Autowired
	private ConsultDao consultDao;
	// 病历记录
	@Autowired
	private PatientMedicalRecordsDao patientMedicalRecordsDao;
	// 病历记录医生输入项
	@Autowired
	private PatientMedicalRecordsItemDao patientMedicalRecordsItemDao;
	// 医生病历片段类型
	@Autowired
	private DoctorMedicalRecordsPartDao doctorMedicalRecordsPartDao;
	// 医生病历片段类型描述内容
	@Autowired
	private DoctorMedicalRecordsPartItemDao doctorMedicalRecordsPartItemDao;
	@Autowired
	private DoctorDao doctorDao;

	/**
	 * 查询医生所有的片段类型
	 * @param doctor 医生标识
	 * @return
	 */
	public List<DoctorMedicalRecordsPart> findPartByDoctor(String doctor) {
		return doctorMedicalRecordsPartDao.findByDoctor(doctor);
	}

	/**
	 * 查询医生指定片段类型下所有的自定义输入项
	 * @param doctor 医生标识
	 * @param part 片段标识
	 * @return
	 */
	public List<DoctorMedicalRecordsPartItem> findPartItemByDoctor(String doctor, String part) {
		return doctorMedicalRecordsPartItemDao.findByDoctor(doctor, part);
	}

	/**
	 * 查询医生的所有片段信息
	 * @param doctor
	 * @return
	 */
	public JSONArray findAllDoctorParts(String doctor) {
		JSONArray array = new JSONArray();
		JSONObject allPartJson = new JSONObject();
		List<DoctorMedicalRecordsPart> parts = doctorMedicalRecordsPartDao.findByDoctor(doctor);
		if (parts != null) {
			for (DoctorMedicalRecordsPart part : parts) {
				if (part == null) {
					continue;
				}
				JSONObject partJson = new JSONObject();
				// 设置片段标识
				partJson.put("code", part.getCode());
				// 设置片段名称
				partJson.put("name", part.getName());
				// 初始化片段字项数组
				partJson.put("items", new JSONArray());
				// 添加到缓存数组中
				allPartJson.put(part.getCode(), partJson);
			}
		}
		List<DoctorMedicalRecordsPartItem> list = doctorMedicalRecordsPartItemDao.findByDoctor(doctor);
		if (list != null) {
			for (DoctorMedicalRecordsPartItem item : list) {
				if (item == null) {
					continue;
				}
				// 片段分类
				JSONObject partJson = null;
				// 判断片段分类是否存在
				if (allPartJson.has(item.getPart())) {
					partJson = allPartJson.getJSONObject(item.getPart());
				}
				// 片段分类不存在
				if (partJson == null) {
					partJson = new JSONObject();
					// 设置片段标识
					partJson.put("code", item.getPart());
					// 设置片段名称
					partJson.put("name", item.getPartName());
					// 初始化片段字项数组
					partJson.put("items", new JSONArray());
					// 添加到缓存数组中
					allPartJson.put(item.getPart(), partJson);
				}
				JSONArray items = partJson.getJSONArray("items");
				// 子项json
				JSONObject itemJson = new JSONObject();
				itemJson.put("id", item.getId());
				// 设置片段标识
				itemJson.put("part", item.getPart());
				// 设置片段自定义内容
				itemJson.put("content", item.getContent());
				items.put(itemJson);
			}
			// 遍历jsonobject
			Iterator<String> iterator = allPartJson.keys();
			while (iterator != null && iterator.hasNext()) {
				String key = iterator.next();
				array.put(allPartJson.getJSONObject(key));
			}
		}
		return array;
	}

	/**
	 * 添加医生自定义片段类型
	 * @param doctor 医生标识
	 * @param name 片段名称
	 * @return
	 */
	public DoctorMedicalRecordsPart addPart(String doctor, String name) {
		DoctorMedicalRecordsPart part = new DoctorMedicalRecordsPart();
		part.setCode(getCode());
		part.setCzrq(new Date());
		part.setDel("1");
		part.setDoctor(doctor);
		part.setName(name);
		return doctorMedicalRecordsPartDao.save(part);
	}

	/**
	 * 添加医生自定义片段输入项
	 * @param doctor 医生标识
	 * @param part 片段标识
	 * @param content 输入项内容
	 * @return
	 */
	public DoctorMedicalRecordsPartItem addPartItem(String doctor, String part, String content) {
		// 查询片段信息
		DoctorMedicalRecordsPart dmrp = doctorMedicalRecordsPartDao.findByCode(part);
		DoctorMedicalRecordsPartItem item = new DoctorMedicalRecordsPartItem();
		item.setContent(content);
		item.setCzrq(new Date());
		item.setDel("1");
		item.setDoctor(doctor);
		item.setPart(part);
		item.setPartName(dmrp.getName());
		return doctorMedicalRecordsPartItemDao.save(item);
	}

	/**
	 * 查询患者的病历片段记录
	 * @param patient
	 * @return
	 */
	public Page<Object> findPatientPartsByDoctor(String doctor, String patient, long id, int pagesize) {
		if (pagesize <= 0) {
			pagesize = 10;
		}
		// 排序
		Sort sort = new Sort(Direction.DESC, "id");
		// 分页信息
		PageRequest pageRequest = new PageRequest(0, pagesize, sort);
		if (id > 0) {
			return patientMedicalRecordsDao.findPatientPartsByDoctor(doctor, patient, id, pageRequest);
		} else {
			return patientMedicalRecordsDao.findPatientPartsByDoctor(doctor, patient, pageRequest);
		}
	}

	/**
	 * 查询患者的病历片段记录
	 * @param patient
	 * @return
	 */
	// public Page<Object> findPartsByPatient(String patient, long id, int pagesize) {
	// if (pagesize <= 0) {
	// pagesize = 10;
	// }
	// // 排序
	// Sort sort = new Sort(Direction.DESC, "id");
	// // 分页信息
	// PageRequest pageRequest = new PageRequest(0, pagesize, sort);
	// if (id > 0) {
	// return patientMedicalRecordsDao.findPartsByPatient(patient, id, pageRequest);
	// } else {
	// return patientMedicalRecordsDao.findPartsByPatient(patient, pageRequest);
	// }
	// }

	/**
	 * 查询患者的病历记录
	 * @param patient
	 * @return
	 */
	public Page<PatientMedicalRecords> findRecordsByPatient(String patient, long id, int pagesize) {
		if (pagesize <= 0) {
			pagesize = 10;
		}
		// 排序
		Sort sort = new Sort(Direction.DESC, "id");
		// 分页信息
		PageRequest pageRequest = new PageRequest(0, pagesize, sort);
		// 设置查询条件
		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
		filters.put("patient", new SearchFilter("patient", Operator.EQ, patient));
		if (id > 0) {
			filters.put("id", new SearchFilter("id", Operator.LT, id));
		}
		filters.put("type", new SearchFilter("type", Operator.EQ, 1));
		// 未作废
		filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
		Specification<PatientMedicalRecords> spec = DynamicSpecifications.bySearchFilter(filters.values(), PatientMedicalRecords.class);
		return patientMedicalRecordsDao.findAll(spec, pageRequest);
	}

	/**
	 * 查询病历信息
	 * @param record
	 * @return
	 */
	public PatientMedicalRecords findRecordByCode(String record) {
		return patientMedicalRecordsDao.findByCode(record);
	}

	/**
	 * 查询病历内容
	 * @param record
	 * @return
	 */
	public List<PatientMedicalRecordsItem> findRecordItemByCode(String record) {
		return patientMedicalRecordsItemDao.findByRecord(record);
	}

	/**
	 * 添加病历片段记录
	 * @param record
	 * @param items
	 */
	public void addPartRecord(String doctor, String patient, String part, String content) {
		// 查询医生信息
		Doctor d = doctorDao.findByCode(doctor);
		// 查询片段信息
		DoctorMedicalRecordsPart dmrp = doctorMedicalRecordsPartDao.findByCode(part);
		PatientMedicalRecords record = new PatientMedicalRecords();
		record.setCode(getCode());
		record.setCzrq(new Date());
		record.setDel("1");
		record.setDoctor(doctor);
		record.setDoctorName(d.getName());
		record.setPatient(patient);
		record.setTitle(dmrp.getName());
		record.setType(2);
		// 记录内容
		PatientMedicalRecordsItem item = new PatientMedicalRecordsItem();
		item.setContent(content);
		item.setCzrq(new Date());
		item.setPart(part);
		item.setPartName(dmrp.getName());
		item.setRecord(record.getCode());
		// 保存到数据库
		patientMedicalRecordsDao.save(record);
		patientMedicalRecordsItemDao.save(item);
	}

	/**
	 * 修改病历片段记录
	 * @param record
	 * @param items
	 */
	public void modifyPartRecord(PatientMedicalRecords record, String content) {
		// 查询原来的片段内容
		PatientMedicalRecordsItem item = patientMedicalRecordsItemDao.findOneByRecord(record.getCode());
		// 记录内容
		item.setContent(content);
		// 保存到数据库
		patientMedicalRecordsDao.save(record);
		// 删除原来的
		patientMedicalRecordsItemDao.save(item);
	}

	/**
	 * 删除病历片段记录
	 * @param code
	 */
	public int deletePartRecord(String doctor, String patient, String code) {
		return patientMedicalRecordsDao.deleteByCode(code);
	}

	/**
	 * 添加病历记录
	 * @param record
	 * @param items
	 */
	public PatientMedicalRecords addRecord(String doctor, String patient, String consult, String title, String parts) {
		// 查询医生信息
		Doctor d = doctorDao.findByCode(doctor);
		PatientMedicalRecords record = new PatientMedicalRecords();
		record.setCode(getCode());
		record.setCzrq(new Date());
		record.setDel("1");
		record.setDoctor(doctor);
		record.setDoctorName(d.getName());
		record.setPatient(patient);
		record.setTitle(title);
		record.setType(1);
		// 查询咨询记录信息
		Consult temp = consultDao.findByCode(consult);
		record.setSymptoms(temp.getSymptoms());
		record.setImages(temp.getImages());
		// 记录内容
		List<PatientMedicalRecordsItem> items = new ArrayList<PatientMedicalRecordsItem>();
		JSONArray array = new JSONArray(parts);
		for (int i = 0; i < array.length(); i++) {
			JSONObject json = array.getJSONObject(i);
			// 查询片段信息
			DoctorMedicalRecordsPart dmrp = doctorMedicalRecordsPartDao.findByCode(json.getString("part"));
			PatientMedicalRecordsItem item = new PatientMedicalRecordsItem();
			item.setContent(json.getString("content"));
			item.setCzrq(new Date());
			item.setPart(dmrp.getCode());
			item.setPartName(dmrp.getName());
			item.setRecord(record.getCode());
			items.add(item);
		}
		// 保存到数据库
		patientMedicalRecordsDao.save(record);
		patientMedicalRecordsItemDao.save(items);
		return record;
	}

}
